package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.SetMealService;
import com.itheima.health.vo.OrderSubmitParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.function.LongFunction;

/**
 * 预约控制器
 */
@RestController
@RequestMapping("/mobile/order")
@Slf4j
public class MobileOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/findById")
    public Result findById(Integer id){
        log.info("订单id为：{}",id);
        //查询数据
        //根据订单id查询订单项
        Order order = orderService.findById(id);
        //根据订单项的成员id查询会员
        Integer memberId = order.getMemberId();
        Member member = memberService.findById(memberId);
        //根据订单项的套餐id查询套餐
        Integer setmealId = order.getSetmealId();
        Setmeal setmeal = setMealService.selectById(setmealId);

        //封装返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("member",member.getName());
        map.put("setmeal",setmeal.getName());
        map.put("orderDate",new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate()));
        map.put("orderType",order.getOrderType());
        return new Result(true, MessageConst.QUERY_ORDER_SUCCESS,map);
    }

    @PostMapping("/submit")
    public Result submit(@RequestBody OrderSubmitParam param){
        log.info("[提交预约信息]data：{}", param);
        String telephone = param.getTelephone();
        if(telephone==null||param.getValidateCode()==null){
            return new Result(false,MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        //1、验证码验证
        //获取前端传过来的验证码
        String validateCode = param.getValidateCode();
        //获取redis中的验证码
        try {
            String redisCode = redisTemplate.opsForValue().get(RedisConst.VALIDATE_CODE_PREFIX + "ORDER" + ":" + param.getTelephone()).toString();
            //判断验证码是否正确
            if(!validateCode.equals(redisCode)){
                return new Result(false,MessageConst.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //如果用户没有点击获取验证码直接输入或者redis中没有保存该手机号的验证码，提示用户验证码发送失败
            throw new BusinessRuntimeException(MessageConst.SEND_VALIDATECODE_FAIL);
        }
        //当验证码正确，日期必须填写
        if(param.getOrderDate()==null){
            throw new BusinessRuntimeException("预约日期不能为空！");
        }
        //这里根据手机号查询会员中是否存在，如果存在说明是老会员，如果不存在说明是新会员，新会员需要注册
        //2、创建会员，把前端的基本会员数据封装到对象中
        Member member = new Member();
        member.setIdCard(param.getIdCard());
        member.setPhoneNumber(param.getTelephone());
        member.setName(param.getName());
        member.setSex(param.getSex());
        //把该对象作为参数，在业务层通过该对象的手机号查询是否为老会员，是老会员就把id给该会员对象，更新会员
        //如果不是老会员，就插入到表中，即注册
        member = memberService.createOrUpdate(member);
        log.info("用户名字为：{}",member.getName());
        //3、提交订单
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(param.getOrderDate());
        //这里默认使用微信预约
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        //默认未到诊
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(param.getSetMealId());
        //在add方法中进行判断是否有这一天的预约时间表，判断预约人数是否已经满了，判断是否预约过，一个人不能在同一天重复预约同一项检查
        order = orderService.add(order);
        //4、返回结果
        return new Result(true, MessageConst.ORDER_SUCCESS,order);
    }

}
